package sjtu.ist.warehouse4ws.security;


import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import sjtu.ist.warehouse4ws.dao.ShiroUserDao;
import sjtu.ist.warehouse4ws.model.ShiroPermission;
import sjtu.ist.warehouse4ws.model.ShiroRole;
import sjtu.ist.warehouse4ws.model.ShiroUser;
import sjtu.ist.warehouse4ws.service.ShiroUserService;





public class MyRealm  extends AuthorizingRealm{

	private ShiroUserService shiroUserService;




	public void setShiroUserService(ShiroUserService shiroUserService) {
		this.shiroUserService = shiroUserService;
	}


	public MyRealm() {

		setName("SampleRealm");  			 		 
	}


	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
//		Long userId = (Long) principals.fromRealm(getName()).iterator().next();  可以返回对象，强制转换让后获取ID
		String username=(String) principals.fromRealm(getName()).iterator().next();
		System.out.print("------principal"+username);
		ShiroUser user = shiroUserService.findUser(username);
		
		if (user != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			for (ShiroRole role : user.getShiroRoles()) {
				info.addRole(role.getRolename());
				for(ShiroPermission p:role.getShiroPermissions()){
					info.addStringPermission(p.getPermission());
				}
			}
			return info;
		} else {
			return null;
		}
	}


	protected AuthenticationInfo doGetAuthenticationInfo (
			AuthenticationToken authcToken) throws AuthenticationException{
		
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		
		ShiroUser user = shiroUserService.findUser(token.getUsername());
		
		if (user != null) {
			return new SimpleAuthenticationInfo(user.getUsername(),
					user.getPassword(), getName());
		
		} else {
			return null;
		}
	}

}
